//数字千分位分隔
export const format = (n: number) => {
    let num: string = n.toString();
    let len: number = num.length;
    if (len <= 3) {
        return num;
    } else {
        let temp: string = '';
        let remainder = len % 3;
        if (remainder > 0) {
            return num.slice(0, remainder) + ',' + num.slice(remainder, len).match(/\d{3}/g)
        } else {
            return num.slice(0, len).match(/\d{3}/g)?.join(',') || '';
        }
    }
}
//全角转换为半角
const toDBC1 = (str: string) => {
    let result: string = '';
    for (let i = 0; i < str.length; i++) {
        let code = str.charCodeAt(i);
        if (code >= 65281 && code <= 65374) {
            result += String.fromCharCode(str.charCodeAt(i) - 65248);
        } else if (code == 12288) {
            result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
        }
        else {
            result += str.charAt(i);
        }
    }
}
//半角转换为全角
const toDBC2 = (str: string): string => {
    let result: string = "";
    for (let i: number = 0; i < str.length; i++) {
        const code: number = str.charCodeAt(i);
        if (code >= 33 && code <= 126) {
            result += String.fromCharCode(code + 65248);
        } else if (code === 32) {
            result += String.fromCharCode(code + 12288 - 32);
        } else {
            result += str.charAt(i);
        }
    }
    return result;
}
//数字转化为中文数字
const intToChinese = (value: number): string => {
    const str: string = String(value);
    const len: number = str.length - 1;
    const idxs: string[] = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿'];
    const num: string[] = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];

    return str.replace(/([1-9]|0+)/g, (match: string, $1: string, idx: number, full: string): string => {
        let pos: number = 0;
        if ($1[0] !== '0') {
            pos = len - idx;
            if (idx === 0 && $1[0] === '1' && idxs[len - idx] === '十') {
                return idxs[len - idx];
            }
            return num[idx] + idxs[len - idx];
        } else {
            let left: number = len - idx;
            let right: number = len - idx + $1.length;
            if (Math.floor(right / 4) - Math.floor(left / 4) > 0) {
                pos = left - left % 4;
            }
            if (pos) {
                return idxs[pos] + num[$1[0]];
            } else if (idx + $1.length >= len) {
                return '';
            } else {
                return num[$1[0]];
            }
        }
    });
};
//存储sessionStorage
const sessionStorageSet = (key: string, value: any) => {
    if (!key) return;
    if (typeof value !== 'string') {
        value = JSON.stringify(value);
    }
    window.sessionStorage.setItem(key, value);
}
//获取sessionStorage
const sessionStorageGet = (key: string) => {
    if (!key) return;
    return window.sessionStorage.getItem(key)
}
//删除sessionStorage
const sessionStorageRemove = (key: string) => {
    if (!key) return;
    window.sessionStorage.removeItem(key)
};
//删除cookie
export const delCookie = (key: string) => {
    document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`
};
//校验是否为中国大陆的邮政编码
const isPostCode = (value: string | number) => {
    return /^[1-9][0-9]{5}$/.test(value.toString());
}
//校验是否为邮箱地址
const isEmail = (value: string) => {
    return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value);
}
//校验是否为中国大陆手机号
const isTel = (value: string | number) => {
    return /^1[3,4,5,6,7,8,9][0-9]{9}$/.test(value.toString());
}
//校验是否包含emoji表情
const isEmojiCharacter = (value: string): boolean => {
    value = String(value);
    for (let i = 0; i < value.length; i++) {
        const hs = value.charCodeAt(i);
        if (0xd800 <= hs && hs <= 0xdbff) {
            if (value.length > 1) {
                const ls = value.charCodeAt(i + 1);
                const uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                if (0x1d000 <= uc && uc <= 0x1f77f) {
                    return true;
                }
            }
        } else if (value.length > 1) {
            const ls = value.charCodeAt(i + 1);
            if (ls == 0x20e3) {
                return true;
            }
        } else {
            if (0x2100 <= hs && hs <= 0x27ff) {
                return true;
            } else if (0x2B05 <= hs && hs <= 0x2b07) {
                return true;
            } else if (0x2934 <= hs && hs <= 0x2935) {
                return true;
            } else if (0x3297 <= hs && hs <= 0x3299) {
                return true;
            } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030
                || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b
                || hs == 0x2b50) {
                return true;
            }
        }
    }
    return false;
};
//修改URL中的参数
const replaceParamVal = (paramName: string, replaceWith: string): string => {
    const oUrl: string = location.href.toString();
    const re: RegExp = new RegExp(`([^&]*)${paramName}([^&]*)`, 'gi');
    location.href = oUrl.replace(re, `${paramName}=${replaceWith}`);
    return location.href;
};
//删除URL中指定参数
const delQueStr = (url: string, ref: string): string => {
    let str: string = "";
    if (url.indexOf('?') != -1) {
        str = url.substr(url.indexOf('?') + 1);
    } else {
        return url;
    }
    let arr: string[] = str.split("&");
    let returnUrl = "";
    let setparam = {};
    return url;
}
//判断是否是苹果还是安卓移动设备
const isAndroidMobileDevice = (): boolean => {
    return /android/i.test(navigator.userAgent.toLowerCase());
}
//判断是否是微信/QQ内置浏览器
const broswer = (): boolean | string => {
    const ua = navigator.userAgent.toLowerCase();
    if (ua.match(/micromessenger/i)) {
        return "weixin";
    } else if (ua.match(/qq/i)) {
        return "QQ";
    }
    return false;
};
//浏览器型号和版本
interface ExplorerInfo {
    type: string;
    version: number;
}

const getExplorerInfo = (): ExplorerInfo => {
    let t = navigator.userAgent.toLowerCase();
    const getMatchNumber = (regex: RegExp) => Number((regex.exec(t) || [])[1]);

    return (
        0 <= t.indexOf("msie") ? {
            type: "IE",
            version: getMatchNumber(/msie ([\d]+)/)
        } :
            !!t.match(/trident\/.+?rv:(([\d.]+))/) ? {
                type: "IE",
                version: 11
            } :
                0 <= t.indexOf("edge") ? {
                    type: "Edge",
                    version: getMatchNumber(/edge\/([\d]+)/)
                } :
                    0 <= t.indexOf("firefox") ? {
                        type: "Firefox",
                        version: getMatchNumber(/firefox\/([\d]+)/)
                    } :
                        0 <= t.indexOf("chrome") ? {
                            type: "Chrome",
                            version: getMatchNumber(/chrome\/([\d]+)/)
                        } :
                            0 <= t.indexOf("opera") ? {
                                type: "Opera",
                                version: getMatchNumber(/opera\/([\d]+)/)
                            } :
                                0 <= t.indexOf("safari") ? {
                                    type: "Safari",
                                    version: getMatchNumber(/version\/([\d]+)/)
                                } :
                                    {
                                        type: t,
                                        version: -1
                                    }
    );
};
//滚动到页面底部
const scrollToBottom = (): void => {
    window.scrollTo(0, document.documentElement.clientHeight);
}
//滚动到指定元素区域
const smoothScroll = (element: string): void => {
    const elementToScroll = document.querySelector(element);
    if (elementToScroll) {
        elementToScroll.scrollIntoView({
            behavior: 'smooth'
        });
    }
}
//获取可视窗口宽度
const getPageViewWidth = (): number => {
    return (document.compatMode == "BackCompat" ? document.body : document.documentElement).clientWidth;
}
//打开浏览器全屏
export const toFullScreen = (): void => {
    let element = document.body;
    if (element.requestFullscreen) {
        element.requestFullscreen()
    }
}
//退出浏览器全屏
const exitFullscreen = (): void => {
    if (document.exitFullscreen) {
        document.exitFullscreen()
    }
}
//当前时间
const nowTime = (): string => {
    const now: Date = new Date();
    const year: number = now.getFullYear();
    const month: number = now.getMonth();
    const date: number | string = now.getDate() >= 10 ? now.getDate() : ('0' + now.getDate());
    const hour: number | string = now.getHours() >= 10 ? now.getHours() : ('0' + now.getHours());
    const miu: number | string = now.getMinutes() >= 10 ? now.getMinutes() : ('0' + now.getMinutes());
    const sec: number | string = now.getSeconds() >= 10 ? now.getSeconds() : ('0' + now.getSeconds());
    return +year + "年" + (month + 1) + "月" + date + "日 " + hour + ":" + miu + ":" + sec;
}
//阻止冒泡事件
const stopPropagation = (e: Event): void => {
    e = e || window.event;
    if (e.stopPropagation) {
        e.stopPropagation();
    } else {
        e.cancelBubble = true;
    }
}
//数据类型判断
const getType = (value: any): string => {
    if (value === null) {
        return value + "";
    }
    if (typeof value === "object") {
        let valueClass = Object.prototype.toString.call(value),
            type = valueClass.split(" ")[1].split("");
        type.pop();
        return type.join("").toLowerCase();
    } else {
        return typeof value;
    }
}